import useDictStore from '@/store/public/dict'
import { getDictInfo } from '@/api/public.js'
import { ref, toRefs } from 'vue'

const dictStore = useDictStore()

export type dictObject = {
  id?: number
  dictLabel: string
  dictValue: string
  showStyle?: string
}

type dictArray = { [key: string]: dictObject[] }

/**
 * 获取字典数据
 */
export function useDict(...args: string[]) {
  const res = ref<dictArray>({})
  return (() => {
    args.forEach((type) => {
      res.value[type] = []
      const dicts = dictStore.getDict(type)
      if (dicts) {
        res.value[type] = dicts
      } else {
        getDictInfo(type).then((response) => {
          res.value[type] = response.data?.map((p) => {
            return {
              dictLabel: p.dictLabel,
              dictValue: p.dictValue,
              showStyle: p.showStyle,
              id: p.id
            }
          })
          dictStore.setDict(type, res.value[type])
        })
      }
    })
    return toRefs<dictArray>(res.value)
  })()
}
